# @Time    :2025/4/8 16:58
"""
            通过starlette框架 构建web服务 uvicorn部署
 相当于java中的   spring                 tomocat
"""
import requests
import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

# 一言网的 API 地址  (海外)
hitokoto_url = 'https://international.v1.hitokoto.cn'


# 定义异步函数来获取随机名言
async def get_hitokoto():
    try:
        params = {
            "c": "a",  # a,代表动画，b代表漫画
            "encode": "json"
        }

        # 获取请求的响应对象
        response = requests.get(hitokoto_url, params=params)
        # 获取状态码
        status_code = response.status_code
        if status_code == 200:
            print(f"请求成功，状态码是{status_code}")
            data = response.json()
            hitokoto = data['hitokoto']
            from_who = data['from_who' if data['from_who'] else '未知']
            return {'hitokoto': hitokoto, 'from_who': from_who}
        else:
            return {'error': f'请求一言网 API 失败，状态码: {status_code}'}
    except requests.RequestException as e:
        return {'error': f'请求过程中出现错误: {str(e)}'}


# 定义处理根路径请求的异步函数
async def homepage(request):
    result = await get_hitokoto()
    return JSONResponse(result)


# 创建Starlette应用实例
app = Starlette(routes=[
    Route('/', homepage),
])
if __name__ == "__main__":
    uvicorn.run(app, host='0.0.0.0', port=8000)
